﻿#region
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using EdmxTransformer.Components;

#endregion

namespace EdmxTransformer.Controls
{
    public class DataGridViewEx : DataGridView, IPresettable
    {
        public void Preset()
        {
            if (RowAddable)
            {
            }
            else
            {
                Columns[0].ReadOnly = true;
                AllowUserToAddRows = false;
                AllowUserToDeleteRows = false;
                AllowUserToOrderColumns = false;
                AllowUserToResizeRows = false;
            }

            MultiSelect = false;
            RowHeadersVisible = false;

            SortByFirstTextColumn();

            HighlightEditableCells();

            KeyUp += DataGridView_KeyUp;
        }

        [DefaultValue(false)]
        public bool RowAddable { get; set; }

        public void SortByFirstTextColumn()
        {
            Sort(Columns[0], ListSortDirection.Ascending);
        }

        private void HighlightEditableCells()
        {
            foreach (DataGridViewColumn column in Columns)
            {
                if (column.ReadOnly || column is DataGridViewTextBoxColumn == false)
                    continue;

                column.DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
            }
        }

        private void DataGridView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (WinformUtility.AskSureToDelete() == false)
                    return;

                DataGridView grid = (DataGridView)sender;
                grid.Rows.RemoveAt(grid.CurrentRow.Index);
            }
        }
    }
}